package com.dk.controller;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dk.Dto.Poweruser;
import com.dk.Util.ExcReadUtil;
import com.dk.Util.JwtUtil;
import com.dk.mapper.UsersMapper;
import com.dk.pojo.Partanduser;
import com.dk.pojo.RESTFUL;
import com.dk.pojo.Users;
import com.dk.service.IPartanduserService;
import com.dk.service.IUsersService;
import com.fasterxml.jackson.core.util.JsonParserSequence;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonArrayFormatVisitor;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2022-07-08
 */
@RestController
@RequestMapping("/users")

public class UsersController {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private IUsersService usersService;
    @Autowired
    private IPartanduserService iPartanduserService;
    @GetMapping("/login")

    public RESTFUL login(String username, String password, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        System.out.println(username+password);
        String requestURI = request.getRequestURI();

        if ( usersService.login(username,password).size()>0){
            // 将登录用户信息保存到session中
                Map<String,String> payload = new HashMap<>();
                payload.put("username",username);
                payload.put("password",password);
                payload.put("id", usersService.login(username,password).get(0).getId().toString());
                //生成JWT令牌
                String token = JwtUtil.getToken(payload);

            Map<String,Object> map=new HashMap<>();

            map.put("token",token);
            return new RESTFUL().SUCCESS(map);
        }else
        {
            return new RESTFUL().FAIL("账号或密码错误");
        }

    }
    @ApiOperation(value = "增加用户")
    @PostMapping("/add")
    public RESTFUL addUsers(@RequestBody Users users){
        System.out.println(users);
//        users.setMaketime(n);
        usersService.save(users);
        return new RESTFUL().SUCCESS();
    }
    @GetMapping("/dele")
    @ApiOperation(value = "删除用户")
    public RESTFUL dele(Integer id){
        usersService.removeById(id);
        return new RESTFUL().SUCCESS();
    }
    @GetMapping("/select")
    @ApiOperation(value = "查询用户")
    public RESTFUL<IPage<Users>> sele(
            String username,
             String name,
             String stat,
            LocalDateTime date,
            Integer ipage,
            Integer size
    ){
        Users users=new Users();
        users.setName(name);
        users.setUsername(username);
        users.setStat(stat);
        users.setMaketime(date);
        System.out.println(users.toString());
        Page page=new Page(ipage,size);
        return new RESTFUL<IPage<Users>>().SUCCESS(usersService.getUserList(page,users));
    }

    @PostMapping("update")
    @ApiOperation(value = "修改用户")
    public RESTFUL update(@RequestBody Users users){
        usersService.updateById(users);
        return new RESTFUL().SUCCESS();

    }

    @PostMapping("readexcl")
    @ResponseBody
    @ApiOperation(value = "导入")
    public RESTFUL upload(MultipartFile file, HttpServletResponse response) throws IOException {
        List<Users> errList=new ArrayList<>();
        try {
            EasyExcel.read(file.getInputStream(), Users.class, new ExcReadUtil(usersService,errList)).sheet().doRead();
        }catch (Exception e){
//            System.out.println(e.getMessage());
            String substring =
        e.getMessage().substring(e.getMessage().indexOf(":") + 2);

            System.out.println(substring);
            List<Users> users = JSONArray.parseArray(substring, Users.class);
            return new RESTFUL().ERR("不符合规则的文件",users);
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            response.setCharacterEncoding("utf-8");
//            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
//            String fileName = URLEncoder.encode("用户表", "UTF-8").replaceAll("\\+", "%20");
//            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
//            EasyExcel.write(response.getOutputStream(), Users.class).sheet("不符合规则的用户表").doWrite(users);

        }
        System.out.println(errList);
        return new RESTFUL().SUCCESS();

    }

    @GetMapping("download")
    @ApiOperation(value = "导出")
    public void download(HttpServletResponse response,
                         String username,
                         String name,
                         String stat) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("用户表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        Users users=new Users();
        users.setUsername(username);
        users.setName(name);
        users.setStat(stat);
        EasyExcel.write(response.getOutputStream(), Users.class).sheet("用户表").doWrite(usersService.getUsersList(users));
    }

    @PostMapping("deleliset")
    @ApiOperation(value = "批量删除")
    public RESTFUL deleList(@RequestBody List<Integer> idList){

        usersService.removeByIds(idList);
        return new RESTFUL().SUCCESS();
    }


    //设置角色
    @PostMapping("gavePart")
    @ApiOperation(value = "设置角色")
    private RESTFUL gavePatt(@RequestBody Poweruser part){
        List<Integer> partId = part.getPartId();
        Integer userid = part.getUserid();
        QueryWrapper<Partanduser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userid",userid);
        iPartanduserService.remove(queryWrapper);
        List<Partanduser> list=new ArrayList<>();
        for (Integer integer : partId) {
            Partanduser partanduser=new Partanduser();
            partanduser.setPartid(integer);
            partanduser.setUserid(userid);
            list.add(partanduser);
        }

        iPartanduserService.saveBatch(list);
        return new RESTFUL().SUCCESS();
    }
    //返回当前用户的角色
    @GetMapping("part")
    @ApiOperation(value = "拥有的角色")
    public RESTFUL getPart(Integer userid){

        return new RESTFUL().SUCCESS(iPartanduserService.getPart(userid));
    }





}
